#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CDN管理器
负责CDN缓存管理和性能优化
"""

import logging
import requests
import time
from typing import Optional, Dict, List

logger = logging.getLogger(__name__)

class CDNManager:
    def __init__(self):
        self.cdn_domain = None
        self.cache_rules = {}
        self._load_config()
    
    def _load_config(self):
        """加载CDN配置"""
        try:
            # 从环境变量获取CDN域名
            self.cdn_domain = os.getenv('CDN_DOMAIN')
            
            if self.cdn_domain:
                logger.info(f"CDN域名: {self.cdn_domain}")
            else:
                logger.warning("CDN域名未配置")
                
        except Exception as e:
            logger.error(f"加载CDN配置失败: {str(e)}")
    
    def get_cdn_url(self, object_key: str) -> str:
        """
        获取CDN URL
        
        Args:
            object_key: COS对象键
            
        Returns:
            str: CDN URL
        """
        if self.cdn_domain:
            return f"https://{self.cdn_domain}/{object_key}"
        else:
            # 如果没有CDN，返回COS直链
            return f"https://your-bucket.cos.ap-guangzhou.myqcloud.com/{object_key}"
    
    def preload_url(self, url: str) -> bool:
        """
        预热CDN缓存
        
        Args:
            url: 需要预热的URL
            
        Returns:
            bool: 预热是否成功
        """
        try:
            logger.info(f"预热CDN缓存: {url}")
            
            # 发送预热请求
            response = requests.get(url, timeout=30)
            
            if response.status_code == 200:
                logger.info("CDN缓存预热成功")
                return True
            else:
                logger.warning(f"CDN缓存预热失败: {response.status_code}")
                return False
                
        except Exception as e:
            logger.error(f"CDN缓存预热异常: {str(e)}")
            return False
    
    def purge_cache(self, urls: List[str]) -> bool:
        """
        刷新CDN缓存
        
        Args:
            urls: 需要刷新的URL列表
            
        Returns:
            bool: 刷新是否成功
        """
        try:
            # TODO: 实现CDN缓存刷新API调用
            logger.info(f"刷新CDN缓存: {len(urls)} 个URL")
            
            # 这里需要调用腾讯云CDN的API
            # 或者使用CDN服务商的API
            
            return True
            
        except Exception as e:
            logger.error(f"CDN缓存刷新异常: {str(e)}")
            return False
    
    def get_cache_status(self, url: str) -> Dict:
        """
        获取缓存状态
        
        Args:
            url: 需要检查的URL
            
        Returns:
            Dict: 缓存状态信息
        """
        try:
            # 发送HEAD请求检查缓存头
            response = requests.head(url, timeout=10)
            
            cache_info = {
                'url': url,
                'status_code': response.status_code,
                'cache_control': response.headers.get('Cache-Control', ''),
                'etag': response.headers.get('ETag', ''),
                'last_modified': response.headers.get('Last-Modified', ''),
                'expires': response.headers.get('Expires', '')
            }
            
            return cache_info
            
        except Exception as e:
            logger.error(f"获取缓存状态异常: {str(e)}")
            return {
                'url': url,
                'error': str(e)
            }
    
    def optimize_delivery(self, object_key: str, file_type: str = 'image') -> Dict:
        """
        优化文件分发
        
        Args:
            object_key: COS对象键
            file_type: 文件类型
            
        Returns:
            Dict: 优化建议
        """
        try:
            cdn_url = self.get_cdn_url(object_key)
            
            # 根据文件类型设置不同的缓存策略
            cache_rules = {
                'image': {
                    'cache_time': 86400 * 30,  # 30天
                    'compress': True,
                    'webp': True
                },
                'video': {
                    'cache_time': 86400 * 7,   # 7天
                    'compress': False,
                    'webp': False
                },
                'document': {
                    'cache_time': 86400,       # 1天
                    'compress': True,
                    'webp': False
                }
            }
            
            rule = cache_rules.get(file_type, cache_rules['image'])
            
            optimization = {
                'cdn_url': cdn_url,
                'cache_time': rule['cache_time'],
                'compress': rule['compress'],
                'webp': rule['webp'],
                'recommendations': []
            }
            
            # 添加优化建议
            if file_type == 'image':
                optimization['recommendations'].extend([
                    '使用WebP格式减少文件大小',
                    '启用图片压缩',
                    '设置长期缓存'
                ])
            
            return optimization
            
        except Exception as e:
            logger.error(f"优化分发异常: {str(e)}")
            return {'error': str(e)}
    
    def monitor_performance(self, url: str) -> Dict:
        """
        监控CDN性能
        
        Args:
            url: 需要监控的URL
            
        Returns:
            Dict: 性能数据
        """
        try:
            start_time = time.time()
            
            response = requests.get(url, timeout=30)
            
            end_time = time.time()
            response_time = end_time - start_time
            
            performance_data = {
                'url': url,
                'response_time': response_time,
                'status_code': response.status_code,
                'content_length': len(response.content),
                'headers': dict(response.headers),
                'timestamp': time.time()
            }
            
            # 计算传输速度
            if response_time > 0:
                performance_data['speed_mbps'] = (
                    len(response.content) * 8 / response_time / 1024 / 1024
                )
            
            return performance_data
            
        except Exception as e:
            logger.error(f"监控CDN性能异常: {str(e)}")
            return {
                'url': url,
                'error': str(e),
                'timestamp': time.time()
            }
